<template>
    <header>
        <div class="search-return" @click="goBack">
            <i class="iconfont icon-fanhui"></i></div>
        <div class="search-main">
            <i class="iconfont icon-fangdajing"></i>
            <form action="" onsubmit="return false" @keyup.enter="goSearchList">
                <input type="search" placeholder="搜索您喜欢的产品..." v-model="searchVal">
            </form>
        </div>
        <div class="search-btn" @click="goSearchList">搜索</div>
    </header>
</template>

<script>
    export default {
        name: "Header",
        data(){
            return {
                searchVal: this.$route.query.key || '',
                searchArr:[]
            }
        },
        methods:{
            goBack(){
                this.$router.back();
            },
            goSearchList(){
                //如果搜索的关键字是没有，那就直接return
                if(!this.searchVal) return;
                //本地存储返回的是字符串格式
                //判断之前有没有搜索的本地存储
                if(!localStorage.getItem('searchList')){
                //    没有
                    localStorage.setItem('searchList','[]');
                }else{
                //    之前有就获取
                    this.searchArr = JSON.parse(localStorage.getItem('searchList'))
                }


                //增加数据，往前放 unshift
                this.searchArr.unshift(this.searchVal);
                //ES6去重
                let newArr =new Set(this.searchArr); //返回是一个对象，但是需要是一个数组
                //把对象转成数组 Array.from
                // console.log(newArr)

                //给本地存储赋值
                localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)));

                console.log( this.searchVal);
                console.log( this.$route.query.key);
                //路径如果没有变化，不跳转页面
                if(this.searchVal === this.$route.query.key) return;
                //跳转页面
                this.$router.push({
                    name:"list",
                    query:{
                        key:this.searchVal
                    }
                })
            }
        }
    }
</script>

<style scoped>
    header{
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 1.173333rem;
        color: #fff;
        background-color: #b0352f;
    }
    .search-return,.search-btn{
        padding: 10px;
    }
    .search-return{
        font-size:14px;
    }
    .search-return i{
        font-size:20px;
    }
    .search-main{
        display: flex;
        align-items: center;
        width: 260px;
        height: 30px;
        border-radius: 12px;
        background-color: #fff;
    }
    .search-main i {
        padding: 0px 10px;
        color: #ccc;
    }
    .search-main form{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
    }
    .search-main form input{
        width: 100%;
    }
    .search-btn{
        font-size:16px;
    }
</style>